﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MvcShop.Models.ViewDataModels;
using MvcShop.Models.Repositories;

namespace MvcShop.Models.Services
{
    public interface IFavoritesService
    {
        IEnumerable<FProductList> GetDefaultFavorites(string userName);
        IEnumerable<FProductList> GetUserFavorites(string userName, int page, int pageSize);
    }

    public class FavoritesService:ServiceBase, IFavoritesService
    {
        public IEnumerable<FProductList> GetDefaultFavorites(string userName)
        {
            var query = (from fa in this.dataContext.Favorites
                         join pro in this.dataContext.Products on fa.ProductId equals pro.ProductId
                         where fa.UserName == userName
                         select new FProductList
                         {
                             ProductId = fa.ProductId,
                             ProductName = pro.ProductName,
                             MarkePrice = pro.MarkePrice,
                             SellPrice = pro.SellPrice,
                             ImageAddress = (from img in this.dataContext.Product_Images 
                                             where img.ProductId==fa.ProductId 
                                             select img.ImageAddress).FirstOrDefault()
                         }).Take(10).ToList();
            return query;
        }

        public IEnumerable<FProductList> GetUserFavorites(string userName, int page, int pageSize)
        {
            var query = (from fa in this.dataContext.Favorites
                         join pro in this.dataContext.Products on fa.ProductId equals pro.ProductId
                         where fa.UserName == userName
                         orderby fa.FavoriteId descending
                         select new FProductList
                         {
                             ProductId = fa.ProductId,
                             ProductName = pro.ProductName,
                             MarkePrice = pro.MarkePrice,
                             SellPrice = pro.SellPrice,
                             ImageAddress = (from img in this.dataContext.Product_Images
                                             where img.ProductId == fa.ProductId
                                             select img.ImageAddress).FirstOrDefault()
                         }).Skip((page - 1) * pageSize).Take(pageSize).ToList();
            return query;
        }
    }
}
